import numpy
from PIL import Image


def way_1(lis, x=35000):
    n = int(lis[4])
    n1 = int((lis[0] + lis[1] + lis[3]) / 3)
    n2 = int((lis[0] + lis[8]) / 2)
    n3 = int((lis[0] + lis[3] + lis[5] + lis[6]) / 4)
    n4 = int((lis[1] + lis[4]) / 2)
    if abs(n1 - n) ** 2 > x or abs(n2 - n) ** 2 > x or abs(n3 - n) ** 2 > x or abs(n4 - n) ** 2 > x:
        return True
    return False

def way_2(center, x=64):
    if center < x:
        return True
    return False

def way_3(lis, x=1):
    num = int(lis[0])+int(lis[1])+int(lis[2])+int(lis[3])+int(lis[5])+int(lis[6])+int(lis[7])+int(lis[8])
    num = int(num/8)
    if lis[4]+x < num:
        return True
    return False


def out(m1, m2, m3):
    img = Image.fromarray(numpy.uint8(m1))
    img.save(img_name + '_1.jpg')

    img = Image.fromarray(numpy.uint8(m2))
    img.save(img_name + '_2.jpg')

    img = Image.fromarray(numpy.uint8(m3))
    img.save(img_name + '_3.jpg')

    m = m1 * 0.3 + m2 * 0.4 + m3 * 0.5
    img = Image.fromarray(numpy.uint8(m))
    img.save(img_name + '_4.jpg')

img_name = '3'
image = Image.open(img_name+'.jpg')
img = image.convert('L')

width, height = img.size
im = numpy.asarray(img)
m1 = im * 0 + 255
m2 = im * 0 + 255
m3 = im * 0 + 255

m4 = im * 0 + 255
m5 = im * 0 + 255
m6 = im * 0 + 255

m7 = im * 0 + 255
m8 = im * 0 + 255
m9 = im * 0 + 255

m11 = im * 0 + 255
m12 = im * 0 + 255
m13 = im * 0 + 255


que = [(-1, -1), (0, -1), (1, -1),
       (-1, 0), (0, 0), (1, 0),
       (-1, 1), (0, 1), (1, 1)]

for i in range(1, height - 1):
    for j in range(1, width - 1):
        lis = []
        for k in que:
            lis.append(im[i + k[0]][j + k[1]])

        if way_1(lis,x=40000):
            m1[i][j] = 0
        elif way_2(lis[4],x=64):
            m2[i][j] = 0
        elif way_3(lis,x=1):
            m3[i][j] = 0

        if way_1(lis, x=35000):
            m4[i][j] = 0
        elif way_2(lis[4], x=62):
            m5[i][j] = 0
        elif way_3(lis, x=10):
            m6[i][j] = 0

        if way_1(lis,x=30000):
            m7[i][j] = 0
        elif way_2(lis[4],x=65):
            m8[i][j] = 0
        elif way_3(lis,x=20):
            m9[i][j] = 0

        if way_1(lis,x=25000):
            m11[i][j] = 0
        elif way_2(lis[4],x=60):
            m12[i][j] = 0
        elif way_3(lis,x=-1):
            m13[i][j] = 0


img_name = str(10)
out(m1,m2,m3)

img_name = str(11)
out(m4,m5,m6)

img_name = str(12)
out(m7,m8,m9)

img_name = str(13)
out(m11,m12,m13)

